#include "pwm.h"
#include "objectlooper.h"

static void __PWM_Loop(PwmDev_t *pwm)
{
    if(!pwm->isRunning)
        return;
        
    pwm->count = (pwm->count + 1) % 100;
    if(pwm->count >= pwm->duty)
    {
        SOC_GpioWrite(pwm->port, pwm->pin, 0);
    }
    else
    {
        SOC_GpioWrite(pwm->port, pwm->pin, 1);
    }
}

void PWM_Init(PwmDev_t *pwm, SOC_GpioPort_t port, int pin)
{
    pwm->duty = 0;
    pwm->count = 0;
    pwm->isRunning = FALSE;
    pwm->port = port;
    pwm->pin = pin;
    
    SOC_GpioInit(port , pin , S_GPIO_Mode_Out_PP);

    RegisterObjectLooper(pwm, 1, __PWM_Loop); 
}

void PWM_SetDuty(PwmDev_t *pwm, uint8_t duty)
{
    pwm->duty = duty;
}

void PWM_Start(PwmDev_t *pwm)
{
    pwm->count = 0;
    pwm->isRunning = TRUE;
}

void PWM_Stop(PwmDev_t *pwm)
{
    pwm->isRunning = FALSE;
    SOC_GpioWrite(pwm->port, pwm->pin, 0);
}
